package com.lianda.mutiple.example;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

//ForkJoin拆分任务
public class ForkJoinMain {
    public static void main(String[] args) {
        //2000个数字的数组
        long[] array = new long[2000];
        long expectSum = 0;
        for (int i = 0; i < array.length; i++) {
            array[i] = random();
        }
//        long[] array =  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//        long expectSum = 0;
        System.out.println("Expected sum: " + expectSum);
        ForkJoinTask<Long> task = new SumTask(array, 0, array.length);
        long startTime = System.currentTimeMillis();
        long result = ForkJoinPool.commonPool().invoke(task);
        long endTime = System.currentTimeMillis();
        System.out.println("Fork/join sum: " + result + " in " + (endTime - startTime) + " ms.");
    }

    static Random random = new Random(0);

    static long random() {
        return random.nextInt(10000);
    }
}

class SumTask extends RecursiveTask<Long> {

    static final int THRESHOLD = 500;
    long[] array;
    int start;
    int end;

    SumTask(long[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {

        if (end - start <= THRESHOLD) {
            //不大的情况下，直接算
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += this.array[i];
                try {
                    //减慢点速度
                    Thread.sleep(100);
                } catch (InterruptedException e) {

                }
            }
            return sum;
        }
        //大任务切分
        int middle = (end + start) / 2;
        System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d",
                start, end, start, middle, middle, end));
        SumTask subTask1 = new SumTask(this.array, start, middle);
        SumTask subTask2 = new SumTask(this.array, middle, end);
        invokeAll(subTask1, subTask2);
        Long subResult1 = subTask1.join();
        Long subResult2 = subTask2.join();
        Long result = subResult1 + subResult2;
        System.out.println("result = "
                + subResult1 + " + " + subResult2
                + " ==> " + result);
        return result;
    }
}
